package org.itboys.mobile.service.mysql.front;

import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.wallet.SundayWalletConchMapper;
import org.itboys.mobile.dto.wallet.SundayWalletDto;
import org.itboys.mobile.entity.mongo.SundayAccount;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.wallet.SundayWallet;
import org.itboys.mobile.entity.mysql.wallet.SundayWalletConch;
import org.itboys.mobile.entity.mysql.wallet.SundayWalletRecord;
import org.itboys.mobile.service.mongo.front.SundayFrontAccountService;
import org.itboys.mobile.service.mongo.front.SundayFrontMemberService;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyang on 2017/12/19.
 * 圣代_钱包_service
 */
@Service
public class SundayFrontWalletService extends BaseMySqlService<SundayWallet>{


    @Autowired
    private SundayFrontWalletRecordService recordService;

    @Autowired
    private SundayFrontCouponService couponService;

    @Autowired
    private SundayFrontAccountService cashAccountService;

    @Autowired
    private SundayFrontMemberService memberService;

    @Autowired
    private SundayWalletConchMapper walletConchMapper;


    /**
     * 根据memberId获取对应的钱包,若没有钱包则自动创建一个
     * @param memberId 用户id
     * @return 钱包
     */
    @Transactional
    public SundayWallet getByMemberId(Long memberId){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberId",memberId);
        List<SundayWallet> walletList = super.select(param);
        SundayWallet wallet = null;
        if(ListUtil.isNotNull(walletList)){
            wallet = walletList.get(0);
        }else{
            wallet = new SundayWallet(memberId);
            super.insert(wallet);
            wallet = super.find(wallet.getId());
        }
        return wallet;
    }

    /**
     * 获取单个钱包dto
     * @param memberId  用户id
     * @return
     */
    public SundayWalletDto getSingleWalletDto(Long memberId,boolean isIndex,boolean isRecord,Integer flag){
        SundayWallet wallet = getByMemberId(memberId);
        SundayWalletDto dto = packageDtoSingle(wallet,isIndex,isRecord,flag);
        return dto;
    }

    /**
     * 组装钱包dto(单)
     * @param wallet
     * @param isIndex 是否组装钱包主页数据
     * @param isRecord 是否组装记录页面数据
     * @return
     */
    public SundayWalletDto packageDtoSingle(SundayWallet wallet,boolean isIndex,boolean isRecord,Integer flag){
      /*  SundayWalletDto dto = new SundayWalletDto();
        dto.setId(wallet.getId());
       // dto.setMemberId(wallet.getMemberId());
        dto.setTotalAmount(wallet.getTotalAmount());
        dto.setAigouCoin(wallet.getAigouCoin());
        dto.setIntegral(wallet.getIntegral());
        //2018年3月5日，增加贝壳
        dto.setConch(wallet.getConch());*/
        //2018年3月9日，使用构造器构造
        SundayWalletDto dto = new SundayWalletDto(wallet.getId(), wallet.getCreateTime(), wallet.getCreateDate(),
                wallet.getTotalAmount(), wallet.getReward(),
                wallet.getIntegral(), wallet.getAigouCoin(),
                wallet.getConch());
        //shou
        //是否加载优惠券
        //是否加载提现账户
        if(isIndex){
            //获取可用的优惠券数量
            Map<String,Object> param= new HashMap<String,Object>();
            param.put("isDeleted", SundayCommonConstants.NO);
            param.put("memberId",wallet.getMemberId());
            param.put("status",SundayCommonConstants.coupon_status_wsy);

            Long couponCount = couponService.count(param);
            dto.setCouponCount(couponCount);

            //获取提现账户数量。2018年3月9日，删除
            /*   param.remove("status");
         Long accountCount = cashAccountService.count(param);;

            dto.setAccountCount(accountCount)*/
        }

        //组装记录页面数据
        if(isRecord){
            dto.setFlag(flag);
            //我的余额,提成
            if(flag == SundayCommonConstants.wallet_type_amount ||
                    flag ==SundayCommonConstants.wallet_type_cash){
                dto.setAmount(wallet.getTotalAmount());
            }else if(flag ==SundayCommonConstants.wallet_type_score){//积分
                dto.setAmount(wallet.getIntegral());
            }else if(flag ==SundayCommonConstants.wallet_type_coin){//爱购币
                dto.setAmount(wallet.getAigouCoin());
            }else if(flag ==SundayCommonConstants.wallet_type_conch){//贝壳
                dto.setAmount(wallet.getConch());
            }else if(flag ==SundayCommonConstants.wallet_type_commission){//提成奖励
                dto.setAmount(wallet.getReward());
            }
        }

        return dto;
    }


    /**
     * 变更钱包:包括变更账户余额,积分,爱购币
     * @param memberId  用户id
     * @param type  变更的类型:
     *              账户余额(1-充值,2-提成,3-购物使用,4-提现),
     *              积分(5-积分兑换,6-购物获得,7-登录获得,8-评论获得,9-分享获得),
     *              爱购币(10-抵扣,11-购物获得,12-分享商品获得,13-展示到社区获得,14-评论获得)
     * @param amount  变更的金额/分数/爱购币数量
     * @param orderNO   订单号
     * @param remark 备注
     * @param account 提现账户,提现时传入
     */
    @Transactional
    public void changeWallet(Long memberId, Integer type, BigDecimal amount, String orderNO,String remark,SundayAccount account){
        //最小数,变更的余额,积分,爱购币,必须大于或等于这个数
        BigDecimal minimunAmount = new BigDecimal("0.01");
        if(amount.compareTo(minimunAmount) == -1){
            return;
        }

        SundayWallet wallet = getByMemberId(memberId);

        BigDecimal negativeOne = new BigDecimal("-1");
        //本次变更的账户余额
        BigDecimal changeTotalAmount = new BigDecimal("0");
        //本次变动的账户提成奖励
        BigDecimal changeReward = new BigDecimal("0");
        //本次变更的积分
        BigDecimal changeIntegral = new BigDecimal("0");
        //本次变更的爱购币
        BigDecimal changeAigouCoin = new BigDecimal("0");
        //本次变更的贝壳
        BigDecimal changeConch = new BigDecimal("0");


        //当前可用金额/分数/爱购币数量
        BigDecimal ableAmount = new BigDecimal("0");
        /*if(type == SundayCommonConstants.wallet_record_type_amount_recharge
                || type ==SundayCommonConstants.wallet_record_type_amount_commission){//账户余额  充值/提成   加
            changeTotalAmount = amount;
            ableAmount=wallet.getTotalAmount();
        }*/
        if(type ==SundayCommonConstants.wallet_record_type_amount_commission) {//账户余额  提成   加
            changeTotalAmount = amount;
            changeReward=amount;
            ableAmount = wallet.getTotalAmount();
        }else if(type == SundayCommonConstants.wallet_record_type_amount_shop
                //提现单独处理
                /*|| type == SundayCommonConstants.wallet_record_type_amount_cash*/){//账户余额  购物使用/提现    减
            amount = amount.multiply(negativeOne);
            changeTotalAmount = amount;
            ableAmount=wallet.getTotalAmount();
        }else if(type == SundayCommonConstants.wallet_record_type_score_shop
                || type == SundayCommonConstants.wallet_record_type_score_login
                || type == SundayCommonConstants.wallet_record_type_score_comment
                || type == SundayCommonConstants.wallet_record_type_score_share){//积分    购物获得/登录获得/评论获得/分享获得     加
            changeIntegral = amount;
            ableAmount=wallet.getIntegral();
        }else if(type == SundayCommonConstants.wallet_record_type_score_exchange){//积分   积分兑换    减
            amount = amount.multiply(negativeOne);
            changeIntegral = amount;
        }else if(type == SundayCommonConstants.wallet_record_type_coin_shop
                || type == SundayCommonConstants.wallet_record_type_coin_share
                || type == SundayCommonConstants.wallet_record_type_coin_show
                || type == SundayCommonConstants.wallet_record_type_coin_comment){//积分   购物获得/分享获得/展示获得/评论获得     加
            changeAigouCoin = amount;
            ableAmount=wallet.getIntegral();
        }else if(type == SundayCommonConstants.wallet_record_type_coin_deduction){//爱购币  抵扣  减
            amount = amount.multiply(negativeOne);
            changeAigouCoin = amount;
            ableAmount=wallet.getAigouCoin();
        }else if(type == SundayCommonConstants.wallet_record_type_conch_charge){//贝壳充值，加
            //amount = amount.multiply(negativeOne);
            changeConch = amount;
            ableAmount=wallet.getAigouCoin();
        }else if(type == SundayCommonConstants.wallet_record_type_conch_charge){//贝壳消费，减
            amount = amount.multiply(negativeOne);
            changeConch = amount;
            ableAmount=wallet.getAigouCoin();
        }

       // logger.info("钱包信息======="+wallet.getTotalAmount()+",本次变动的总金额"+changeTotalAmount+",新的余额"+(wallet.getTotalAmount().add(changeTotalAmount)));
        wallet.setTotalAmount(wallet.getTotalAmount().add(changeTotalAmount));
        //2018年3月9日，增加提成
        wallet.setReward(wallet.getReward().add(changeReward));
        wallet.setIntegral(wallet.getIntegral().add(changeIntegral));
        wallet.setAigouCoin(wallet.getAigouCoin().add(changeAigouCoin));
        wallet.setConch(wallet.getConch().add(changeConch));
        super.update(wallet);

        //生成钱包变动记录
        SundayWalletRecord record = new SundayWalletRecord();
       // SundayMember member = memberService.getById(memberId);
        record.setMemberId(memberId);
        record.setWalletId(wallet.getId());
        record.setType(type);
        record.setAmount(amount);
        //2018年2月28日，增加当前可用金额/分数/爱购币数量
        record.setAbleAmount(ableAmount);
        record.setOrderNo(orderNO);
        record.setRemark(remark);
       // record.setMemberNickName(member.getNickName());
        //如果类型为账户余额充值,则默认状态为无效(即预充值),其他都为有效
        if(type == SundayCommonConstants.wallet_record_type_amount_recharge){
            record.setStatus(SundayCommonConstants.NO);
        }else{
            record.setStatus(SundayCommonConstants.YES);
        }

        //提现设置记录的提现信息
        //提现单独处理
        /*if(record.getType()==SundayCommonConstants.wallet_record_type_amount_cash){
            record.setAccountStatus(SundayCommonConstants.INCOME_YSQ);
            record.setAccountOpentId(member.getWeixinOpenId());
            //内部付款流水号，用户重复调用微信企业付款
            record.setAccountNo(NumberUtil.generateNumber("CASH"));
            record.setAccountType();
           // record.setac
        }*/
        /*if(account != null){
            record.setAccountType(account.getType());
            record.setAccountStatus(SundayCommonConstants.INCOME_YSQ);
            record.setAccountNo(account.getAccount());
            record.setAccountRealName(member.getRealName());
        }*/
        recordService.insert(record);
    }

    /**
     * 提现申请
     * @param cashAmount
     * @param memberId
     * @param accountType 2微信开放平台，3微信公众号（针对app）
     */
    @Transactional
    public void saveCash(BigDecimal cashAmount,Long memberId,Integer accountType){
        //校验是否有提现账户
      /*  Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);*/
     /*   Long count = cashAccountService.count(param);

        if(accountId == null || accountId == 0L){
            throw new ErrorException("您未选择提现账户");
        }*/
      /*  if(amount == null){
            throw new ErrorException("您未输入提现金额");
        }*/

       /* SundayAccount account = cashAccountService.getById(accountId);*/
       //校验用户是否有openId
        SundayMember member = memberService.getById(memberId);
        if(!StringUtils.isNotEmpty(member.getWeixinOpenId())){
            throw new ErrorException("缺少微信必要参数，请使用微信重新登陆");
        }
        SundayWallet wallet = getByMemberId(memberId);
        //金额校验
        if(cashAmount.compareTo(wallet.getTotalAmount()) == 1){
            throw new ErrorException("当前最大提现金额为:"+wallet.getTotalAmount());
        }else{
            if(cashAmount.compareTo(new BigDecimal("1")) == -1){
                throw new ErrorException("当前最低提现金额为:1元。");
            }
        }
        //当前可用金额
        BigDecimal ableAmount = new BigDecimal("0");

        wallet.setTotalAmount(wallet.getTotalAmount().subtract(cashAmount));
        super.update(wallet);
        //生成记录
        BigDecimal negativeOne = new BigDecimal("-1");
        SundayWalletRecord record = new SundayWalletRecord();

        record.setMemberId(memberId);
        record.setWalletId(wallet.getId());
        record.setType(SundayCommonConstants.wallet_record_type_amount_cash);
        record.setAbleAmount(ableAmount);
        record.setStatus(SundayCommonConstants.YES);
        //2018年2月28日，增加当前可用金额/分数/爱购币数量
        record.setAmount(cashAmount.multiply(negativeOne));
        record.setRemark("用户:"+memberId+"申请提现,金额为:"+cashAmount);
        record.setAccountStatus(SundayCommonConstants.INCOME_YSQ);
        //用户opentId
        record.setAccountOpenId(member.getWeixinOpenId());
        //内部付款流水号，用户重复调用微信企业付款
        record.setAccountNo(NumberUtil.generateNumber("CASH"));
        record.setAccountType(accountType);
        recordService.insert(record);
    }

    /**
     * 贝壳充值
     * @param code
     */
    @Transactional
    public void conch_charge(String code,Long memberId){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("status",SundayCommonConstants.NO);
        param.put("code",code);
        List<SundayWalletConch> walletConchs=walletConchMapper.select(param);
        if(ListUtil.isNull(walletConchs)){
            throw new ErrorException("贝壳编码无效。");
        }
        SundayWalletConch walletConch=walletConchs.get(0);
        SundayMember member =memberService.getById(memberId);
        walletConch.setStatus(SundayCommonConstants.YES);
        walletConch.setMemberId(memberId);
        walletConch.setOpenId(member.getWeixinOpenId());
        walletConchMapper.update(walletConch);
        //生成充值记录
        changeWallet( memberId,SundayCommonConstants.wallet_record_type_conch_charge,
                walletConch.getAmount(), walletConch.getCode(),"贝壳充值",null);
    }
}
